<?php
namespace App\Services\WxCard;

use App\Facades\EasyWechat;
use App\Models\WxCardQrcode;
use App\Services\WxCommon\WxError;

/**
 * 微信卡券投放二维码服务类
 * @package App\Services
 */
class WxCardQrcodeService extends \App\Services\WxCommon\WxBase
{
    const TYPE_QR_CARD = 'QR_CARD';//单张卡券二维码
    const TYPE_QR_MULTIPLE_CARD = 'QR_MULTIPLE_CARD';//多张卡券

    const STATUS_EDITING = 0;//编辑中
    const STATUS_PUBLISHED = 1;//已发布

    protected $typeList = [];

    /**
     * 构造函数
     */
    public function __construct($appid = '')
    {
        parent::__construct($appid);

        $this->typeList = [
            self::TYPE_QR_CARD => '单张卡券二维码',
            self::TYPE_QR_MULTIPLE_CARD => '多张卡券二维码',
        ];
    }

    /**
     * 获取类别列表
     * @return array
     */
    public function getTypeList()
    {
        $list = [];
        foreach ($this->typeList as $key => $name){
            $list[] = ['type'=>$key,'name'=>$name];
        }
        return $list;
    }

    /**
     * 获取二维码类型名
     * @param $type
     * @return mixed|string
     */
    public function getTypeStr($type)
    {
        return $this->typeList[$type] ?? '';
    }
    /**
     * 获取二维码状态名
     * @param $status
     * @return mixed|string
     */
    public function getStatusStr($status)
    {
        $statusList = [
            self::STATUS_EDITING => '编辑中',
            self::STATUS_PUBLISHED => '已发布',
        ];
        return $statusList[$status] ?? '';
    }
    /**
     * 保存投放二维码
     * @param $request
     * @return bool
     * @throws \Exception
     */
    public function save($request)
    {
        $qrcodeId = $request->id ?? 0;
        if ($qrcodeId){
            $qrcodeModel = WxCardQrcode::where('appid', $this->appid)->findOrFail($qrcodeId);
            if ($qrcodeModel->status_is == self::STATUS_PUBLISHED){
                throw new \Exception('该二维码已发布，不允许编辑');
            }
        }else{
            $qrcodeModel = new WxCardQrcode;
        }
        $qrcodeModel->appid = $this->appid;
        $qrcodeModel->type = $request->type ?? '';
        $qrcodeModel->title = $request->title ?? '';
        $qrcodeModel->card_info = (array) $request->card_info ?? [];
        $qrcodeModel->card_list = (array) $request->card_list ?? [];
        $qrcodeModel->qrcode_info = [];
        $qrcodeModel->status_is = self::STATUS_EDITING;
        return $qrcodeModel->save();
    }

    /**
     * 生成二维码
     * @param $qrcodeId
     * @return mixed
     * @throws \Exception
     */
    public function publish($qrcodeId)
    {
        $qrcodeModel = WxCardQrcode::where('appid', $this->appid)->findOrFail($qrcodeId);
        $apiPostData = [];
        //单张卡券
        if ($qrcodeModel->type == self::TYPE_QR_CARD){
            $apiPostData['action_name'] = self::TYPE_QR_CARD;
            if ($qrcodeModel->card_info['expire_type'] == 'defa'){
                $apiPostData['expire_seconds'] = (int) $qrcodeModel->card_info['expire_seconds'];
            }
            $apiPostData['action_info']['card'] = [];
            !empty($qrcodeModel->card_info['card_id']) && $apiPostData['action_info']['card']['card_id'] = $qrcodeModel->card_info['card_id'];
            !empty($qrcodeModel->card_info['code']) && $apiPostData['action_info']['card']['code'] = $qrcodeModel->card_info['code'];
            !empty($qrcodeModel->card_info['openid']) && $apiPostData['action_info']['card']['openid'] = $qrcodeModel->card_info['openid'];
            if ($qrcodeModel->card_info['is_unique_code']){
                $apiPostData['action_info']['card']['is_unique_code'] = (bool) $qrcodeModel->card_info['is_unique_code'];
            }
            !empty($qrcodeModel->card_info['outer_str']) && $apiPostData['action_info']['card']['outer_str'] = $qrcodeModel->card_info['outer_str'];
        }
        //多张卡券
        if ($qrcodeModel->type == self::TYPE_QR_MULTIPLE_CARD){
            $apiPostData['action_name'] = self::TYPE_QR_MULTIPLE_CARD;
            $apiPostData['action_info']['multiple_card']['card_list'] = [];
            if (!empty($qrcodeModel->card_list)){
                $cardList = [];
                foreach ($qrcodeModel->card_list as $card){
                    $cardData = [];
                    !empty($card['card_id']) && $cardData['card_id'] = $card['card_id'];
                    !empty($card['code']) && $cardData['code'] = $card['code'];
                    !empty($card['outer_str']) && $cardData['outer_str'] = $card['outer_str'];
                    $cardList[] = $cardData;
                }
                $apiPostData['action_info']['multiple_card']['card_list'] = $cardList;
            }
        }
        //调用接口创建二维码
        $app = EasyWechat::officialAccount($this->appid);
        $apiRs = $app->card->createQrCode($apiPostData);
        WxError::checkApiResponse($apiRs);
        $qrcodeModel->qrcode_info = $apiRs;
        $qrcodeModel->status_is = self::STATUS_PUBLISHED;
        return $qrcodeModel->save();
    }

    /**
     * 删除二维码
     * @param $qrcodeId
     * @return mixed
     */
    public function destory($qrcodeId)
    {
        $cardModel = WxCardQrcode::where('appid', $this->appid)->findOrFail($qrcodeId);
        return $cardModel->delete();
    }
}